<template>
  <!-- 主容器 -->
  <div class="article-container">
    <!-- 页面头部 -->
    <div class="header">
      <!-- 文章标题 -->
      <h1>{{ article.title }}</h1>
      <!-- 返回按钮 -->
      <button @click="goBack" class="back-button">返回</button>
    </div>
    <!-- 文章元信息 -->
    <div class="article-meta">
      <span>分区：{{ article.category }}</span>
      <span>作者：{{ article.writer }}</span>
      <span>发布时间：{{ article.publishTime }}</span>
      <span>点赞数：{{ article.like }}</span>
      <span>评论数：{{ article.comment }}</span>
      <span>收藏数：{{ article.favorite }}</span>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
      <div class="right-actions">
        <button @click="likeArticle" class="like-button">点赞</button>
        <button @click="favoriteArticle" class="favorite-button">收藏</button>
        <button @click="openReportModal" class="report-button">举报</button>
      </div>
    </div>
    <!-- 文章内容 -->
    <div class="article-content">
      <div class="content-box">
        <p>{{ article.content }}</p>
      </div>
    </div>
    <!-- 评论区 -->
    <div class="comment-section">
      <button @click="openCommentModal" class="comment-button">评论</button>
    </div>

    <!-- 评论列表 -->
    <div class="comments-list">
      <h3>评论列表</h3>
      <div v-if="comments.length === 0" class="no-comments">暂无评论</div>
      <div v-for="(comment, index) in comments" :key="index" class="comment-item">
        <div class="comment-header">
          <span class="comment-author">用户：{{ comment.comment }}</span>
        </div>
        <div class="comment-content">
          {{ comment.reader }}
        </div>
      </div>
    </div>

    <!-- 评论弹窗 -->
    <div v-if="showCommentModal" class="modal show">
      <div class="modal-content">
        <span class="close-button" @click="closeCommentModal">&times;</span>
        <h2>发表评论</h2>
        <div class="form-group">
          <textarea v-model="comment" placeholder="请输入评论内容"></textarea>
        </div>
        <div class="modal-actions">
          <button @click="submitComment" class="submit-button">上传</button>
          <button @click="closeCommentModal" class="cancel-button">取消</button>
        </div>
      </div>
    </div>

    <!-- 举报弹窗 -->
    <div v-if="showReportModal" class="modal show">
      <div class="modal-content">
        <span class="close-button" @click="closeReportModal">&times;</span>
        <h2>举报文章</h2>
        <div class="form-group">
          <textarea v-model="report" placeholder="请输入举报内容"></textarea>
        </div>
        <div class="modal-actions">
          <button @click="submitReport" class="submit-button">上传举报</button>
          <button @click="closeReportModal" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';

export default defineComponent({
  setup() {
    const router = useRouter();
    const route = useRoute();

    // 解析文章数据
    const article = JSON.parse(route.query.article as string);

    return { router, article };
  },
  data() {
    return {
      showCommentModal: false, // 评论弹窗显示状态
      showReportModal: false, // 举报弹窗显示状态
      comment: '', // 评论内容
      report: '', // 举报内容
      comments: [], // 评论列表
    };
  },
  methods: {
    // 返回按钮点击事件
    goBack() {
      this.router.back();
    },
    // 点赞按钮点击事件
    likeArticle() {
      this.sendFeedback(2); // 点赞类型数为2
    },
    // 收藏按钮点击事件
    favoriteArticle() {
      this.sendFeedback(4); // 收藏类型数为4
    },
    // 打开评论弹窗
    openCommentModal() {
      this.showCommentModal = true;
    },
    // 关闭评论弹窗
    closeCommentModal() {
      this.showCommentModal = false;
      this.comment = '';
    },
    // 打开举报弹窗
    openReportModal() {
      this.showReportModal = true;
    },
    // 关闭举报弹窗
    closeReportModal() {
      this.showReportModal = false;
      this.report = '';
    },
    // 提交评论
    submitComment() {
      if (this.comment.trim() === '') {
        alert('评论内容不能为空！');
        return;
      }
      this.sendFeedback(3, this.comment); // 评论类型数为3
      this.closeCommentModal();
    },
    // 提交举报
    submitReport() {
      if (this.report.trim() === '') {
        alert('举报内容不能为空！');
        return;
      }
      this.sendReport(); // 提交举报
      this.closeReportModal();
    },
    // 发送反馈到后端
    sendFeedback(status: number, comment?: string) {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        alert('请先登录！');
        return;
      }

      const feedbackData = {
        writer: this.article.writer,
        title: this.article.title,
        currentUsername: username,
        status: status,
        comment: comment || ''
      };

      // 发送请求到后端
      fetch('http://localhost:8080/lzl_content2_war_exploded/userFeedback', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(feedbackData)
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          alert(data.message); // 显示后端返回的消息
          if (data.success) {
            // 更新文章数据
            if (status === 2) {
              this.article.like++;
            } else if (status === 3) {
              this.article.comment++;
              // 提交评论后刷新评论列表
              this.fetchComments();
            } else if (status === 4) {
              this.article.favorite++;
            }
          }
        })
        .catch(error => {
          console.error('Error sending feedback:', error);
          alert('操作时出错！');
        });
    },
    // 发送举报到后端
    sendReport() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        alert('请先登录！');
        return;
      }

      const reportData = {
        reporter: username, // 举报人
        articleWriter: this.article.writer, // 文章作者
        articleTitle: this.article.title, // 文章标题
        articleCategory: this.article.category, // 文章分区
        reportContent: this.report // 举报内容
      };

      // 发送请求到后端
      fetch('http://localhost:8080/lzl_content2_war_exploded/userReport', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(reportData)
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          alert(data.message); // 显示后端返回的消息
        })
        .catch(error => {
          console.error('Error sending report:', error);
          alert('举报时出错！');
        });
    },
    // 获取评论数据
    fetchComments() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        alert('请先登录！');
        return;
      }

      // 发送请求到后端获取评论
      fetch(`http://localhost:8080/lzl_content2_war_exploded/userGetComments?writer=${this.article.writer}&title=${this.article.title}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            this.comments = data.comments;
            console.log('Fetched comments:', this.comments); // 调试日志，检查获取到的数据
          } else {
            alert(data.message);
          }
        })
        .catch(error => {
          console.error('Error fetching comments:', error);
          alert('获取评论时出错！');
        });
    }
  },
  mounted() {
    // 组件加载时获取评论数据
    this.fetchComments();
  }
});
</script>

<style scoped>
.article-container {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h1 {
  margin: 0;
  color: #333;
}

.back-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #45a049;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin: 10px 0;
  color: #666;
}

.article-meta span {
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.right-actions {
  display: flex;
  gap: 10px;
}

.like-button, .favorite-button, .report-button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.like-button {
  background-color: #ff9800;
}

.favorite-button {
  background-color: #2196F3;
}

.report-button {
  background-color: #f44336;
}

.report-button:hover {
  background-color: #d32f2f;
}

.article-content {
  margin-top: 20px;
  border: 1px solid #ccc;
  padding: 20px;
  background-color: #f9f9f9;
  overflow: auto;
  max-height: calc(100vh * 3 / 4);
  width: calc(100% * 3 / 4);
  margin-left: auto;
  margin-right: auto;
}

.content-box {
  white-space: pre-line;
  line-height: 1.6;
}

.comment-section {
  margin-top: 20px;
  text-align: right;
}

.comment-button {
  background-color: #9C27B0;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.comment-button:hover {
  background-color: #7B1FA2;
}

/* 弹窗样式 */
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.modal.show {
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  max-width: 500px;
  width: 100%;
  position: relative;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 15px;
  font-size: 24px;
  cursor: pointer;
}

.form-group {
  margin-bottom: 15px;
}

textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  height: 150px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.submit-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-button {
  background-color: #f1f1f1;
  color: #333;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

/* 评论列表样式 */
.comments-list {
  margin-top: 30px;
  border: 1px solid #ccc;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 5px;
}

.comments-list h3 {
  margin-top: 0;
  color: #333;
}

.no-comments {
  color: #666;
  text-align: center;
  padding: 20px;
}

.comment-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.comment-author {
  font-weight: bold;
  color: #2196F3;
}

.comment-time {
  color: #666;
  font-size: 0.9em;
}

.comment-content {
  line-height: 1.6;
}
</style>